package com.tpvlog.dfs.namenode.log;

import com.tpvlog.dfs.namenode.file.FSNameSystem;

import java.io.File;
import java.util.List;

/**
 * Edits Log清理线程
 */
public class EditLogCleaner extends Thread {
    private static final Long EDIT_LOG_CLEAN_INTERVAL = 30 * 1000L;

    private FSNameSystem nameSystem;

    public EditLogCleaner(FSNameSystem nameSystem) {
        super();
        this.nameSystem = nameSystem;
    }

    @Override
    public void run() {
        System.out.println("edits log日志文件后台清理线程启动......");

        while (true) {
            try {
                Thread.sleep(EDIT_LOG_CLEAN_INTERVAL);
                List<String> flushedTxids = nameSystem.getEditsLog().getFlushedTxids();
                if (flushedTxids != null && flushedTxids.size() > 0) {
                    // 获取最近一次checkpoint
                    long checkpointTxid = nameSystem.getCheckpointTxid();
                    for (String flushedTxid : flushedTxids) {
                        long startTxid = Long.valueOf(flushedTxid.split("_")[0]);
                        long endTxid = Long.valueOf(flushedTxid.split("_")[1]);

                        // 在最近一次checkpoint之前的edits log文件都要删除
                        if (checkpointTxid >= endTxid) {
                            File file = new File("C:\\Users\\Ressmix\\Desktop\\editslog\\edits-"
                                    + startTxid + "-" + endTxid + ".log");
                            if (file.exists()) {
                                file.delete();
                                System.out.println("发现editlog日志文件不需要，进行删除：" + file.getPath());
                            }
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
